package com.dykj.fireFighting.web.base.analysis.controller;


import com.dykj.fireFighting.api.base.analysis.dto.ComprehensiveQueryDto;
import com.dykj.fireFighting.api.base.maintenance.service.IUrgentMaintenanceService;
import com.dykj.fireFighting.api.base.maintenance.vo.MaintenanceEvaluationVo;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.utils.DateBetweenUtil;
import com.dykj.fireFighting.common.core.utils.UUIDUtils;
import com.dykj.fireFighting.common.core.vo.LoginUserVo;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 综合查询-机构
 */
@Slf4j
@Api(value = "机构评分", tags = {"机构评分接口"})
@RestController
@RequestMapping("/zongheorg")
public class ZongHeOrgController {


    @DubboReference
    private IUrgentMaintenanceService urgentMaintenanceService;


    /**
     * echarts数据排名榜
     *
     * @param comprehensiveQueryDto
     * @return
     */
    @GetMapping("/rankingEcharts")
    public CommonResult<PageVo<MaintenanceEvaluationVo>> getData(ComprehensiveQueryDto comprehensiveQueryDto) throws ParseException {
        List<MaintenanceEvaluationVo> resultSocreList = new ArrayList<>();

        //获取用户类型，监控中心查下辖的单位，社会单位查自己，管理员查全部社会单位
        LoginUserVo loginUserVo = ShiroUtil.getUser();
        String jkzxUnitId = loginUserVo.getEnterpriseId().toString();

        List<String> unitIdList = new ArrayList<>();
        if (StringUtils.isNotBlank(comprehensiveQueryDto.getUnitIds())) {
            String[] unitIds = comprehensiveQueryDto.getUnitIds().split(",");
            unitIdList = Arrays.asList(unitIds);
        } else {
            unitIdList.add("");
        }

        //时间段月份
        List<String> monthList = DateBetweenUtil.getMonthBetween(comprehensiveQueryDto.getBeginTime(), comprehensiveQueryDto.getEndTime());
        //获取数据
        for (String unitId : unitIdList) {
            for (String s : monthList) {
                String date = s.substring(0, 7) + "-01";
                List<MaintenanceEvaluationVo> monthSocreList = urgentMaintenanceService.queryMaintenanceEvaluationAvgList(jkzxUnitId, unitId, date);
                resultSocreList.addAll(monthSocreList);
            }
        }

        //list排序
        //根据某个属性分组，汇总某个属性
        Map<String, BigDecimal> resultMap = new HashMap<>();
        if ("1".equals(comprehensiveQueryDto.getDataDimension())) {
            resultMap = resultSocreList.stream().collect(Collectors.groupingBy(MaintenanceEvaluationVo::getMaintenanceName, Collectors.reducing(BigDecimal.ZERO, MaintenanceEvaluationVo::getMonthAvgScore, BigDecimal::add)));
        } else if ("2".equals(comprehensiveQueryDto.getDataDimension())) {
            resultMap = resultSocreList.stream().collect(Collectors.groupingBy(MaintenanceEvaluationVo::getAreaName, Collectors.reducing(BigDecimal.ZERO, MaintenanceEvaluationVo::getMonthAvgScore, BigDecimal::add)));
        } else {
            resultMap = resultSocreList.stream().collect(Collectors.groupingBy(MaintenanceEvaluationVo::getIndustryName, Collectors.reducing(BigDecimal.ZERO, MaintenanceEvaluationVo::getMonthAvgScore, BigDecimal::add)));
        }

        List<MaintenanceEvaluationVo> resultList = new ArrayList<>();
        resultMap.forEach((key, value) -> {
            MaintenanceEvaluationVo result = new MaintenanceEvaluationVo();
            result.setName(key);
            result.setTotalScore(value.intValue());
            resultList.add(result);
        });

        //list排序
        Integer[] arr = {1};
        List<MaintenanceEvaluationVo> returnSocreList = resultList.stream().sorted(Comparator.comparing(MaintenanceEvaluationVo::getTotalScore).reversed())
                .peek(e -> e.setRanking(arr[0]++)).collect(Collectors.toList());

        //split page
        long page = comprehensiveQueryDto.getPage();
        long limit = comprehensiveQueryDto.getLimit();
        List<MaintenanceEvaluationVo> subList = returnSocreList.stream().skip((page - 1) * limit).limit(limit).collect(Collectors.toList());
        PageVo<MaintenanceEvaluationVo> pageVo = new PageVo<>();
        pageVo.setList(subList);
        pageVo.setTotalCount(returnSocreList.size());
        return CommonResult.success(pageVo);
    }


    /**
     * echarts数据
     *
     * @param comprehensiveQueryDto
     * @return
     * @throws Exception
     */
    @GetMapping("/trendEcharts")
    public CommonResult getRankingEchartsData(ComprehensiveQueryDto comprehensiveQueryDto) throws Exception {
        Map<String, Object> resultData = new HashMap<>();
        Map<String, List<Double>> resultMap = new HashMap<>();
        List<MaintenanceEvaluationVo> resultSocreList = new ArrayList<>();

        //获取用户类型，监控中心查下辖的单位，社会单位查自己，管理员查全部社会单位
        LoginUserVo loginUserVo = ShiroUtil.getUser();
        String jkzxUnitId = loginUserVo.getEnterpriseId().toString();

        List<String> unitIdList = new ArrayList<>();
        if (StringUtils.isNotBlank(comprehensiveQueryDto.getUnitIds())) {
            String[] unitIds = comprehensiveQueryDto.getUnitIds().split(",");
            unitIdList = Arrays.asList(unitIds);
        } else {
            unitIdList.add("");
        }

        //时间段月份
        List<String> monthList = new ArrayList<>();
        if ("1".equals(comprehensiveQueryDto.getTimeGranularity())) {
            monthList = DateBetweenUtil.getYearBetween(comprehensiveQueryDto.getBeginTime(), comprehensiveQueryDto.getEndTime());
        } else if ("2".equals(comprehensiveQueryDto.getTimeGranularity())) {
            monthList = DateBetweenUtil.getSeasonList(comprehensiveQueryDto.getBeginTime(), comprehensiveQueryDto.getEndTime());
        } else {
            monthList = DateBetweenUtil.getMonthBetween(comprehensiveQueryDto.getBeginTime(), comprehensiveQueryDto.getEndTime());
        }

        //获取数据
        List<MaintenanceEvaluationVo> monthSocreList = new ArrayList<>();
        String beginTime = comprehensiveQueryDto.getBeginTime();
        String endTime = comprehensiveQueryDto.getEndTime();
        int index = 0;
        for (String unitId : unitIdList) {
            index++;
            boolean nums = index == unitIdList.size();
            for (int x = 0; x < monthList.size(); x++) {
                if ("1".equals(comprehensiveQueryDto.getTimeGranularity())) {
                    String year = monthList.get(x).substring(0, 4);
                    for (int i = 1; i < 13; i++) {
                        String date = year + "-" + UUIDUtils.int2str(i) + "-01";
                        //if (beginTime < date && date < endTime) {
                        monthSocreList = urgentMaintenanceService.queryMaintenanceEvaluationAvgList(jkzxUnitId, unitId, date);
                        //}
                    }
                    monthList.set(x, year);
                } else if ("2".equals(comprehensiveQueryDto.getTimeGranularity())) {
                    int year = Integer.parseInt(monthList.get(x).substring(0, 4));
                    int month = Integer.parseInt(monthList.get(x).substring(5, 7));
                    for (int i = 0; i < 3; i++) {
                        int num = month + i;
                        String date = year + "-" + UUIDUtils.int2str(num) + "-01";
                        monthSocreList = urgentMaintenanceService.queryMaintenanceEvaluationAvgList(jkzxUnitId, null, date);
                    }
                    if (nums) {
                        int quarter = (month + 2) / 3;
                        monthList.set(x, year + "-" + quarter);
                    }
                } else {
                    String date = monthList.get(x).substring(0, 7) + "-01";
                    monthSocreList = urgentMaintenanceService.queryMaintenanceEvaluationAvgList(jkzxUnitId, unitId, date);
                    monthList.set(x, monthList.get(x).substring(0, 7));
                }
                //list排序
                //根据某个属性分组，汇总某个属性
                Map<String, BigDecimal> monthResult = new HashMap<>();
                if ("1".equals(comprehensiveQueryDto.getDataDimension())) {
                    monthResult = monthSocreList.stream().collect(Collectors.groupingBy(MaintenanceEvaluationVo::getMaintenanceName, Collectors.reducing(BigDecimal.ZERO, MaintenanceEvaluationVo::getMonthAvgScore, BigDecimal::add)));
                } else if ("2".equals(comprehensiveQueryDto.getDataDimension())) {
                    monthResult = monthSocreList.stream().collect(Collectors.groupingBy(MaintenanceEvaluationVo::getAreaName, Collectors.reducing(BigDecimal.ZERO, MaintenanceEvaluationVo::getMonthAvgScore, BigDecimal::add)));
                } else {
                    monthResult = monthSocreList.stream().collect(Collectors.groupingBy(MaintenanceEvaluationVo::getIndustryName, Collectors.reducing(BigDecimal.ZERO, MaintenanceEvaluationVo::getMonthAvgScore, BigDecimal::add)));
                }
                for (Map.Entry<String, BigDecimal> entry : monthResult.entrySet()) {
                    if (resultMap.containsKey(entry.getKey())) {
                        List<Double> resultList = resultMap.get(entry.getKey());
                        BigDecimal one = entry.getValue();
                        double two = one.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        resultList.add(two);
                        resultMap.put(entry.getKey(), resultList);
                    } else {
                        List<Double> resultList = new ArrayList<>();
                        BigDecimal one = entry.getValue();
                        double two = one.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        resultList.add(two);
                        resultMap.put(entry.getKey(), resultList);
                    }
                }

            }
        }
        resultData.put("month", monthList);
        resultData.put("data", resultMap);
        return CommonResult.success(resultData);
    }


}
